package com.qf.fmall2202.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.fmall2202.product.entity.Product;
import com.qf.fmall2202.product.entity.ProductImg;
import com.qf.fmall2202.product.mapper.ProductMapper;
import com.qf.fmall2202.product.service.IProductImgService;
import com.qf.fmall2202.product.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 商品信息相关表：分类表，商品图片表，商品规格表，商品参数表 服务实现类
 * </p>
 *
 * @author dong_
 * @since 2022-11-07
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    IProductImgService productImgService;


    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Product> listRecommends() {

        //1. 创建分页对象
        final Page<Product> productPage = new Page<>(1,3);

        productPage.addOrder(OrderItem.desc("create_time"));

        this.page(productPage);

        final List<Product> productList = productPage.getRecords();

        // 处理商品对应的图片信息的填充

        // 查询这三个商品对应所有图片信息
        final QueryWrapper<ProductImg> productImgQueryWrapper = new QueryWrapper<>();

        // List<Product> --> List<ProductID>
        final List<String> productIdList = productList.stream().map(Product::getProductId).collect(Collectors.toList());

        productImgQueryWrapper.in("item_id",productIdList);

        final List<ProductImg> productImgsList = productImgService.list(productImgQueryWrapper);


        // 分组 List<ProductImg>  ---> Map<商品ID， List<商品图片> >
        final Map<String, List<ProductImg>> productImgMap = productImgsList.stream()
                .collect(Collectors.groupingBy(ProductImg::getItemId));

        // 填充 productList
        productList.forEach(product -> product.setImgs(productImgMap.get(product.getProductId())));

        return productList;
    }
}
